using System;
using Slaks.DocumentSerialization.Document;
using Slaks.DocumentSerialization.TermIdInfo;

namespace Slaks.Graphs.GraphBuilder.Slaks
{
	/// <summary>
	/// Summary description for NormalizedFrequencyRepresentationSlaks.
	/// </summary>
	public class NormalizedFrequencyRepresentationSlaks : SlaksBuilder
	{
		#region IRepresentation Members

		protected override  Graph Build(Document document, int numberOfVerticesToLeave,int nParameter, TermIdInfoMap map)
		{
			Graph graph = base.Build(document,numberOfVerticesToLeave,nParameter,map);
			string documentName = document.FileName;
			int index = documentName.LastIndexOfAny(new char[] {'\\', '/'});
			if (index >= 0 && (index + 1 < documentName.Length)) documentName = documentName.Substring(index + 1);

			graph.Name = documentName;
			Graph tempGraph = this.BuildTemporalGraph(document, BuilderType.NormalizedFrequencyRepresentationSlaks);
			this.RemoveInfrequentVerticesInTemporalGraph(tempGraph, numberOfVerticesToLeave);

			Vertex vertex;
			string sectionType;

			long frequentNode = int.MinValue;

			#region find frequent node

			long mostFrequentId = document.MostFrequencyInfo.TotalMostFrequentId;
			frequentNode = document.GetNodeById(mostFrequentId).TotalTermFrequency;

			#endregion

			//iterate through nodes
			foreach (Node node in document.Nodes)
			{
				//check if the vertex is in the list of frequent nodes.
				if (tempGraph.GetVertex(node.Id) == null) continue;
				vertex = graph.CreateAddVertex(node.Id);
				vertex.Frequency = (double) node.TotalTermFrequency/frequentNode;

				//iterate through sections
				foreach (Section section in node.Sections)
				{
					sectionType = section.GetSectionTypeString();

					Section.SectionType sectionTp = Section.GetSectionTypeByString(sectionType);

					//iterate through sentences
					foreach (Sentence sentence in section.Sentences)
					{
						AddRelations(document, graph, tempGraph, vertex, 1, 1, sentence, sectionTp, BuilderType.NormalizedFrequencyRepresentationSlaks);
					}
				}
			}

			#region set normalized frequency to the edge

			VertexList vertexList = graph.GetVertexList();
			double mostFrequentEdge = long.MinValue;
			double tempEdgeFrequency = 0;
			foreach (Vertex ver in vertexList)
			{
				tempEdgeFrequency = 0;
				foreach (EdgeList edgeLst in ver.GetSection2EdgeMap().Values)
				{
					foreach (Edge edge in edgeLst)
					{
						tempEdgeFrequency += edge.GetFrequency();
					}
				}

				if (mostFrequentEdge < tempEdgeFrequency) mostFrequentEdge = tempEdgeFrequency;
			}

			//set the normalized frequency
			foreach (Vertex ver in vertexList)
			{
				foreach (EdgeList edgeLst in ver.GetSection2EdgeMap().Values)
				{
					foreach (Edge edge in edgeLst)
					{
						edge.SetFrequency(edge.GetFrequency()/mostFrequentEdge);
					}
				}
			}

			#endregion

			return graph;
		}


		#endregion
	}
}